import { useUserStore } from "@/stores/useUserStore";
import { filterBaseUrl } from "@/utils/common";

// 添加拦截器
const httpInterceptor = {
	// 拦截前触发
	invoke(options: UniApp.RequestOptions) {
		// 1.非http
		if (!options.url.startsWith("http")) {
			options.url = filterBaseUrl(options.url) + options.url;
		}
		// 2.添加请求头
		options.header = {
			...options.header,
			"source-client": "miniapp",
		};

		// 3.添加token请求头标识
		if (uni.getStorageSync("token")) {
			const token =
				uni.getStorageSync("tokenTypeStore") +
				" " +
				uni.getStorageSync("token");
			options.header.Authorization = token;
		}
	},
};
uni.addInterceptor("request", httpInterceptor);
uni.addInterceptor("uploadFile", httpInterceptor);

interface Data<T> {
	code: string;
	msg: string;
	result?: T;
	data?: T;
}
// 添加类型，支持泛型
export const http = <T>(options: UniApp.RequestOptions) => {
	// 加载提示
	let loading = options?.loading;
	// 如果有loading就显示loading
	if (loading) {
		uni.showLoading(loading);
	}
	// 返回Promise对象
	return new Promise<Data<T>>((resolve, reject) => {
		uni.request({
			...options,
			// 2.请求成功
			success(res: any) {
				const { code, message } = res.data;
				if (code === 200) {
					resolve(res.data as Data<T>);
				} else if (res.data instanceof ArrayBuffer) {
					// 响应数据为二进制流处理(Excel导出)
					resolve(res);
				} else if (code === 401) {
					uni.showModal({
						title: "提示",
						content: "由于您长时间未操作，请重新登录",
						showCancel: false,
						success: function (res) {
							if (res.confirm) {
								useUserStore().logout();
							} else if (res.cancel) {
								console.log("用户点击取消");
							}
						},
					});
				} else {
					// 其他错误
					uni.showToast({
						icon: "none",
						title: message || "系统出错",
					});
					reject(res);
				}
			},
			// 3.请求失败
			fail(err: any) {
				if (err?.response?.status === 401) {
					uni.showModal({
						title: "提示",
						content: "由于您长时间未操作，请重新登录",
						success: function (res) {
							if (res.confirm) {
								useUserStore().logout();
							} else if (res.cancel) {
								console.log("用户点击取消");
							}
						},
					});
				} else {
					uni.showToast({
						title: "网络错误",
						icon: "none",
					});
				}
				reject(err);
			},
			complete() {
				// 完成 关闭loading
				if (loading) {
					uni.hideLoading();
				}
			},
		});
	});
};
